// Modules to control application life and create native browser window
const {app, Menu, BrowserWindow, Tray ,globalShortcut, ipcMain,Notification} = require('electron')
const path = require('path')
const createHttpRequest = require('./js/createHttpRequest');

function createWindow () {
	
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
	frame: false,
	maximizable: true,
    minimizable: true,
    resizable: true,
	skipTaskbar: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
	  nodeIntegration: true,
	  webviewTag:true
    }
  })

 // mainWindow.webContents.openDevTools();
  // and load the index.html of the app.
  mainWindow.loadFile('index.html')
    // 最小化窗口
    ipcMain.on('min-win', () => {
        mainWindow.minimize()
    })

    // 最大化窗口
    ipcMain.on('max-win', () => {
        mainWindow.maximize()
        // 禁止手动调整窗口大小
        mainWindow.setResizable(false)
    })

    // 恢复窗口大小
    ipcMain.on('restore-win', () => {
        mainWindow.unmaximize()
        // 禁止手动调整窗口大小
        mainWindow.setResizable(true)
    })

    // 关闭窗口
    ipcMain.on('close-win', () => {
        mainWindow.hide()
    })
    ipcMain.on('window-settings', () => {
        mainWindow.loadFile('settings.html')
        new Notification({ title: "Hello World!", body: "这是一个通知测试。" }).show();
    })


    // 取消 win.close() 默认事件
    mainWindow.on('close', (event) => {
        event.preventDefault()
        mainWindow.hide()
    })
  // Open the DevTools.
 //  mainWindow.webContents.openDevTools()
   mainWindow.on('close', function (e) {
	  e.preventDefault();
	  mainWindow.hide();
	})
   mainWindow.on('window-closed', function () {
    mainWindow = null;
  })
    // 注册 F5 快捷键刷新页面
    globalShortcut.register('F5', () => {
        mainWindow.reload()
    })

    // 注册 F10 快捷键打开开发者工具
    globalShortcut.register('F10', () => {
        mainWindow.webContents.openDevTools()
    })

    mainWindow.webContents.on('before-input-event', (event, input) => {
        if (input.control && input.key.toLowerCase() === 'r') {
            mainWindow.reload()
        }
        if (input.control && input.shift && input.key.toLowerCase() === 'i') {
            mainWindow.webContents.openDevTools()
        }
    })

    mainWindow.webContents.session.on('will-download', (event, item) => {
        let fileName = item.getFilename()
        let fileExtension = path.extname(fileName)
        let baseName = path.basename(fileName, fileExtension)
        let savePath = path.join(app.getPath('downloads'), fileName)

        // if file already exists, add a number to the filename
        let counter = 1;
        while (fs.existsSync(savePath)) {
            let newFileName = `${baseName}_${counter}${fileExtension}`
            savePath = path.join(app.getPath('downloads'), newFileName)
            fileName = newFileName
            counter++;
        }

        item.setSavePath(savePath)

        item.once('done', async (event, state) => {
            if (state === 'completed') {
                dialog.showMessageBox({
                    title: '文件下载',
                    message: `文件 ${fileName} 已经下载成功 ${app.getPath('downloads')}`,
                })

                try {
                    await shell.openPath(savePath)
                } catch (err) {
                    dialog.showErrorBox('File Open Failed', `File ${fileName} could not be opened. ${err.message}`)
                }
            } else {
                dialog.showErrorBox('File Download Failed', `File ${fileName} download failed.`)
            }
        })
    })
  return mainWindow
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  Menu.setApplicationMenu(null)
 const mainWindow = createWindow()
  
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) mainWindow =  createWindow()
  })
  const tray = new Tray(path.join(__dirname,"./favicon.png"));
  const contextMenu = Menu.buildFromTemplate([
    { label: '退出', click:function(){app.quit()} },
	{ label: '最小化', click:function(){mainWindow.minimize()} },
	{ label: '最大化', click:function(){mainWindow.maximize()} },
	{ label: '打开', click:function(){mainWindow.restore()} } , //取消最小化函数（从最小化窗口还原函数）
	{ label: '设置', click:function(){mainWindow.loadFile('settings.html')} },
    { label: '开发模式', click:function(){  mainWindow.webContents.openDevTools()} }
  ])
//  remote.getCurrentWindow().maximize();
//remote.getCurrentWindow().minimize();
//remote.getCurrentWindow().unmaximize();
//remote.getCurrentWindow().restore();

    // 设置鼠标移入托盘显示文字
  tray.setToolTip('西瓜在线V1.0')
  tray.setContextMenu(contextMenu)
   app.on('window-closed', function () {
       console.log("window btnClose click")
	  if (process.platform !== 'darwin') app.quit()
	})
}) 
 
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})
app.on('will-quit', () => {
    //注销所有全局快捷键
    globalShortcut.unregisterAll()
})

app.on('ready', function()  {
    //autoUpdater.checkForUpdatesAndNotify();
    createWindow();
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
//监听渲染进程的http请求
ipcMain.handle('httpRequest', async (event, query) => {
    const  res  = await createHttpRequest(query);
    return res;
})